requirejs.config({
	paths: {
		jquery: '/static/js/jquery',
		datatables: '/static/datatables/js/jquery.dataTables.min',
		bootstrap: '/static/bootstrap/js/bootstrap.min'
	}
});
require(['jquery'], function() {
	var Messages, oe = {
		init: function(){
			this.initLogin();
			//load required lib
			require([/*'datatables', */'bootstrap']);
		},
		initLogin: function(){
			if(window.username) {
				oe.showMain();
				$('#username-placeholder').text(window.username);
				return;
			}
			$('#do-login').click(function(){
				var username = $('#login-username'),
					password = $('#login-password'),
					usernameStr = username.val();
				if(oe.validate(username[0]) !== true || oe.validate(password[0]) !== true) {
					return;
				}
				oe.login(usernameStr, password.val(), function(){
					oe.showMain();
					$('#username-placeholder').text(usernameStr);
				});
			});
			$('#login-container').keydown(function(e){
				if(e.keyCode === 13) {
					e.stopPropagation();
					$('#do-login').trigger('click');
				}
			});
		},
		showMain: function(){
			$('#login-container').remove();
			$(document.body).removeClass('body-login');
			$('#menu').show();
			$('#view-store').show();
			oe.initMainEvents();
			oe.updateStoreViewer();
		},
		initMainEvents: function(){
			$('#menu').delegate('[action]', 'click', function(e){
				var me = $(this), action = me.attr('action');
				switch(action) {
					case 'in':
						oe.showIn();
						break;
					case 'out':
						oe.showOut();
						break;
					case 'left':
						me.closest('li').siblings('.active').removeClass('active').end().addClass('active');
						$('#view-log').hide();
						$('#view-store').show();
						oe.updateStoreViewer();
						break;
					case 'detail':
						me.closest('li').siblings('.active').removeClass('active').end().addClass('active');
						$('#view-log').show();
						$('#view-store').hide();
						oe.updateLogViewer();
						break;
				}
			});
		},
		updateStoreViewer: function(){
			this.api.listProducts(function(e, data){
				if(!data) { return; }
				$('#view-store').find('tbody').html($.map(data, function(d){
					return '<tr><td>' + d.number + '</td><td>' + d.name + '</td><td>' + d.model_name + '</td><td>' + d.category + '</td><td>' + d.location + '</td><td>' + d.count + '</td></tr>';
				}).join(''));
			});
		},
		updateLogViewer: function(){
			this.api.listLogs(function(e, data){
				if(!data) { return; }
				$('#view-log').find('tbody').html($.map(data, function(d){
					return '<tr><td>' + d.operation_datetime
						+ '</td><td>' + d.product__number
						+ '</td><td>' + d.product__name
						+ '</td><td>' + d.product__model_name
						+ '</td><td>' + d.operation_type
						+ '</td><td>' + d.count
						+ '</td><td>' + d.remain
						+ '</td><td>' + d.product__category
						+ '</td><td>' + d.user
						+ '</td><td>' + d.remark
						+ '</td></tr>';
				}).join(''));
			});
		},
		login: function(username, password, callback){
			$.post('/login/', {username: username, password: password}, function(data){
				if(typeof data == "string") { data = $.parseJSON(data); }
				if(data.status == "success") {
					callback(true);
				} else {
					oe.alert(data.msg || "登录失败");
				}
			});
		},
		validate: function(el){
			var $el = $(el), v = $.trim(el.value), tmp, ret;
			if($el.attr('required') && !v.length) {
				ret = Messages.required
			} else if((tmp=$el.attr('number')) && !/^[1-9]\d*$/.test(tmp)) {
				ret = Messages.number;
			} else {
				ret = true;
			}
			if(ret === true) {
				$el.siblings('.help-block').text('');
				$el.closest('.control-group').removeClass('error');
			} else {
				$el.siblings('.help-block').text(ret);
				$el.closest('.control-group').addClass('error');
			}
			return ret;
		},
		showIn: function(){
			var modal = $('#in-modal');
			if(!modal.data('modal')) {
				modal.modal({keyboard: false});
				modal.on('hidden', function(){
					var fm = $(this).children('.modal-body').children('form')[0];
					fm.reset();
				});
				modal.delegate('[action]', 'click', function(){
					var me = $(this), action = me.attr('action'), fm, data, flag = false;
					if(action == "submit") {
						data = {};
						fm = me.closest('.modal-footer').siblings('.modal-body').children('form');
						$.each(fm[0].elements, function(_, el){
							if(el.name) {
								if(oe.validate(el) !== true) {
									flag = true;
									return false;
								} else {
									data[el.name] = el.value;
								}
							}
						});
						if(!flag) {
							oe.api.enter(data);
						}
					}
					$('#in-modal').modal('hide');
				});
				modal.find('.dropdown-menu').delegate('li', 'click', function(){
					var me = $(this), input;
					input = me.closest('.btn-group').siblings('input');
					input.val(me.attr('data-number'));
					input.trigger('blur');
				});
				modal.find('[name=number]').blur(function(){
					var num = this.value, fm;
					fm = this.form;
					oe.api.checkNumber(num, function(exist){
						if(exist) {
							$(fm.name).removeAttr('required').closest('.control-group').hide();
							$(fm.model_name).removeAttr('required').closest('.control-group').hide();
							$(fm.category).removeAttr('required').closest('.control-group').hide();
							$(fm.unit).removeAttr('required').closest('.control-group').hide();
							$(fm.location).removeAttr('required').closest('.control-group').hide();
						} else {
							$(fm.name).attr('required', 'required').closest('.control-group').show();
							$(fm.model_name).attr('required', 'required').closest('.control-group').show();
							$(fm.category).attr('required', 'required').closest('.control-group').show();
							$(fm.unit).attr('required', 'required').closest('.control-group').show();
							$(fm.location).attr('required', 'required').closest('.control-group').show();
						}
						fm = null;
					});
				});
			}
			modal.modal('show');
			oe.api.listNumbers(function(e, data){
				var dict;
				if(e) { return; }
				else {
					modal.find('.dropdown-menu').html($.map(data, function(d){
						return '<li data-number="' + d + '"><a href="#">' + d + '</a></li>';
					}).join(''));
				}
			});
		},
		showOut: function(){
			var modal = $('#out-modal');
			if(!modal.data('modal')) {
				modal.modal({keyboard: false});
				modal.on('hidden', function(){
					var fm = $(this).children('.modal-body').children('form')[0];
					fm.reset();
				});
				modal.delegate('[action]', 'click', function(){
					var me = $(this), action = me.attr('action'), fm, data, flag = false;
					if(action == "submit") {
						data = {};
						fm = me.closest('.modal-footer').siblings('.modal-body').children('form');
						$.each(fm[0].elements, function(_, el){
							if(el.name) {
								if(oe.validate(el) !== true) {
									flag = true;
									return false;
								} else {
									data[el.name] = el.value;
								}
							}
						});
						if(!flag) {
							oe.api.deliver(data);
						}
					}
					$('#out-modal').modal('hide');
				});
				modal.find('.dropdown-menu').delegate('li', 'click', function(){
					var me = $(this), input;
					input = me.closest('.btn-group').siblings('input');
					input.val(me.attr('data-number'));
				});
			}
			modal.modal('show');
			oe.api.listNumbers(function(e, data){
				if(e) { return; }
				else {
					modal.find('[name=number]').html($.map(data, function(d){
						return '<option value="' + d + '">' + d + '</option>';
					}).join(''));
				}
			});
		},
		alert: function(str, level){
			var classname, html, el, onRemove;
			el = $('#oe-alert');
			if(el.length) {
				el.remove();
			}
			if(level) {
				classname = "alert-" + level;
			} else {
				classname = "";
			}
			html = '<div id="oe-alert" class="alert ' + classname + ' oe-alert"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>' + str + '</strong></div>';
			$(html).appendTo(document.body);
			el = $('#oe-alert');
			el.css({marginTop: -1*el.height(), marginLeft: -1*el.width()});
			el.animate({marginTop: 0});
			onRemove = function(){
				el.animate({marginTop: -1*el.height()}, function(){
					el.remove();
				});
			};
			el.delegate('.close', 'click', onRemove);
			setTimeout(onRemove, 3000);
		},
		api: {
			enter: function(data){
				$.post('/store/enter/', data, function(resp){
					console.log(resp);
				});
			},
			deliver: function(data){
				$.post('/store/deliver/', data, function(resp){
					console.log(resp);
				});
			},
			checkNumber: function(num, callback){
				if(num === "" || typeof num == "undefined") { return; }
				$.get('/product/check/?number=' + num, function(data){
					if(typeof data == "string") {
						data = $.parseJSON(data);
					}
					if(data.status == "success") {
						callback(data.exist);
					} else {
						callback(false);
					}
				});
			},
			listNumbers: function(callback){
				$.get('/product/number/list/', function(data){
					if(typeof data == "string") {
						data = $.parseJSON(data);
					}
					if(data.status == "success") {
						callback(null, data.data.records);
					} else {
						callback("error");
					}
				});
			},
			listProducts: function(callback){
				$.get('/product/list/', function(data){
					if(typeof data == "string") {
						data = $.parseJSON(data);
					}
					if(data.status == "success") {
						callback(null, data.data.records);
					} else {
						callback("error");
					}
				});
			},
			listLogs: function(callback){
				$.get('/operation-log/list/', function(data){
					if(typeof data == "string") {
						data = $.parseJSON(data);
					}
					if(data.status == "success") {
						callback(null, data.data.records);
					}
				})
			}
		}
	};
	$(function(){ oe.init(); });
	Messages = {
		required: "必须填写",
		remote: "请修正此栏位",
		email: "请输入有效的电子邮件",
		url: "请输入有效的网址",
		date: "请输入有效的日期",
		dateISO: "请输入有效的日期 (YYYY-MM-DD)",
		number: "请输入正确的数字",
		digits: "只可输入数字",
		creditcard: "请输入有效的信用卡号码",
		equalTo: "你的输入不相同",
		extension: "请输入有效的后缀",
		maxlength: "最多 {0} 个字",
		minlength: "最少 {0} 个字",
		rangelength: "请输入长度为 {0} 至 {1} 之間的字串",
		range: "请输入 {0} 至 {1} 之间的数值",
		max: "请输入不大于 {0} 的数值",
		min: "请输入不小于 {0} 的数值"
	};
});